/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.analyze;

import cn.ac.nercis.pes.common.constant.evaluation.EvaluationModule;
import cn.ac.nercis.pes.common.constant.knowledge.TargetType;
import cn.ac.nercis.pes.common.constant.project.FinishState;
import cn.ac.nercis.pes.common.constant.project.SystemState;
import cn.ac.nercis.pes.community.component.controls.MenuListCell;
import cn.ac.nercis.pes.community.component.dialog.MessageDialog;
import cn.ac.nercis.pes.community.component.dialog.MessageType;
import cn.ac.nercis.pes.community.component.dialog.PageDialog;
import cn.ac.nercis.pes.community.component.dialog.SpinnerDialog;
import cn.ac.nercis.pes.community.component.spreadsheet.analyze.UnitEvalSheetView;
import cn.ac.nercis.pes.community.controller.base.GlobalEventHandle;
import cn.ac.nercis.pes.community.controller.base.InitEvalDataLoad;
import cn.ac.nercis.pes.community.controller.dialog.UnitRecordController;
import cn.ac.nercis.pes.community.manager.RealTimeSaveManager;
import cn.ac.nercis.pes.community.mapper.evaluation.UnitEvaluationViewMapper;
import cn.ac.nercis.pes.community.model.vo.MenuVO;
import cn.ac.nercis.pes.community.model.vo.evaluation.UnitEvaluationVO;
import cn.ac.nercis.pes.community.utils.ControlUtils;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.community.views.dialog.UnitRecordView;
import cn.ac.nercis.pes.model.dto.common.DataCopy;
import cn.ac.nercis.pes.model.dto.common.DataPaste;
import cn.ac.nercis.pes.model.dto.project.SystemProcessDTO;
import cn.ac.nercis.pes.model.dto.target.LayerTargetDTO;
import cn.ac.nercis.pes.service.evaluation.UnitEvaluationService;
import cn.ac.nercis.pes.community.service.paste.AnalyzePasteService;
import cn.ac.nercis.pes.service.project.SystemProcessService;
import cn.ac.nercis.pes.service.project.SystemTargetService;
import javafx.application.Platform;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;

/**
 * 单元测评管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class UnitEvalController implements Initializable, GlobalEventHandle, InitEvalDataLoad {

    protected final static Integer MAX_SHOW_MENU_TEXT_LENGTH = 10;

    @FXML
    private StackPane page;
    @FXML
    private ListView<MenuVO> tecMenus;
    @FXML
    private ListView<MenuVO> manageMenus;
    @FXML
    private Label currentLayerTargetLbl;
    @FXML
    private Button tmpSaveButton;
    @FXML
    private Button saveButton;
    @FXML
    private UnitEvalSheetView sheetView;

    @FXML
    private VBox unitResultAnalysisBox;
    @FXML
    private AnchorPane emptyPane;
    @FXML
    private ImageView emptyImageView;
    @FXML
    private Label emptyLabel;

    private final SystemTargetService systemTargetService;
    private final UnitEvaluationService unitEvaluationService;
    private final SystemProcessService systemProcessService;

    private final AnalyzePasteService analyzePasteService;
    private final ExecutorService executor;
    private final RealTimeSaveManager realTimeSaveManager = new RealTimeSaveManager(this::realTimeSave);

    private MenuVO currentLayerTarget;
    private String currentSystemId;
    private final BooleanProperty enablePaste = new SimpleBooleanProperty(false);

    public UnitEvalController() {
        this.systemTargetService = SpringUtils.getBean(SystemTargetService.class);
        this.unitEvaluationService = SpringUtils.getBean(UnitEvaluationService.class);
        this.systemProcessService = SpringUtils.getBean(SystemProcessService.class);
        this.analyzePasteService = SpringUtils.getBean(AnalyzePasteService.class);
        this.executor = SpringUtils.getBean(ExecutorService.class);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        saveButton.setGraphic(IconUtils.getGlyph("save-button-icon","btn-icon"));
        tmpSaveButton.setGraphic(IconUtils.getGlyph("temp-save-button-icon","btn-icon"));
        ControlUtils.initEmptyImageView(this.emptyImageView,log);
        unitResultAnalysisBox.managedProperty().bind(unitResultAnalysisBox.visibleProperty());
        emptyPane.managedProperty().bind(emptyPane.visibleProperty());
        this.initMenuControls();
        GuiStore.applyQuickSave(this.page, this::onGlobalSave);
        realTimeSaveManager.listenerSheetChange(this.sheetView);
    }

    @Override
    public void initializeData(String systemId){
        this.currentSystemId = systemId;
        LogUtils.info(log, "初始化单元测评信息...");
        this.loadMenuData();
        this.sheetView.initialize(this::onShowRecordButtonClick);
    }

    @Override
    public void onGlobalSave() {
        LogUtils.info(log, "执行快捷保存操作...");
        onTmpSave();
    }

    @FXML
    public void onTmpSave(){
        LogUtils.info(log, "执行暂存操作...");
        batchSaveUnitEvaluation(false,false);
    }

    @FXML
    public void onFinishSave() {
        LogUtils.info(log, "执行保存操作...");
        batchSaveUnitEvaluation(false,true);
    }

    public void realTimeSave(){
        LogUtils.info(log, "执行即时保存操作...");
        batchSaveUnitEvaluation(true, false);
    }

    public void onShowRecordButtonClick(UnitEvaluationVO unitEvaluation){
        LogUtils.info(log, "执行查看测评记录操作...");
        var recordView = AppStore.getEvaluationView(this.currentSystemId, UnitRecordView.class);
        PageDialog pageDialog = PageDialog.builder()
                .withTitle("测评记录")
                .withShowActions(false)
                .withContent(Objects.requireNonNull(recordView).load())
                .withOwner(AppStore.getCurrentSystem(this.currentSystemId).getEvaluationStage())
                .withOverlayClose(true)
                .build();
        if(recordView.getController() instanceof UnitRecordController controller){
            controller.initializeData(this.currentSystemId,unitEvaluation.getUnitTargetId());
        }
        pageDialog.show();
    }

    private void initMenuControls() {
        tecMenus.setContextMenu(this.generateReportContextMenu());
        tecMenus.setOnContextMenuRequested(eve -> this.onReportContextMenuRequested());
        tecMenus.setCellFactory(cf -> new MenuListCell(true));
        tecMenus.getSelectionModel().selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    if (Objects.nonNull(newValue)) {
                        manageMenus.getSelectionModel().clearSelection();
                        loadUnitEvaluation(newValue);
                    }
                });
        manageMenus.setContextMenu(this.generateReportContextMenu());
        manageMenus.setOnContextMenuRequested(eve -> this.onReportContextMenuRequested());
        manageMenus.setCellFactory(cf -> new MenuListCell(true));
        manageMenus.getSelectionModel().selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    if (Objects.nonNull(newValue)) {
                        tecMenus.getSelectionModel().clearSelection();
                        loadUnitEvaluation(newValue);
                    }
                });
    }



    private ContextMenu generateReportContextMenu() {
        final ContextMenu contextMenu = new ContextMenu();
        contextMenu.getStyleClass().add("pes-context-menu");
        final MenuItem copyItem = new MenuItem("复制", IconUtils.getGlyph("cell-copy-icon", "context-menu-icon"));
        copyItem.setOnAction(e -> this.onDataCopyAction());
        final MenuItem pasteItem = new MenuItem("粘贴", IconUtils.getGlyph("cell-paste-icon", "context-menu-icon"));
        pasteItem.disableProperty().bind(enablePaste.not());
        pasteItem.setOnAction(e -> this.onDataPasteAction());
        contextMenu.getItems().addAll(copyItem, pasteItem);
        return contextMenu;
    }

    private void onDataPasteAction() {
        LogUtils.info(log, "执行数据粘贴操作...");
        var dataCopy = DataCopyUtils.getClipboard();
        if (Objects.isNull(dataCopy)) {
            AppUtils.showMessageDialog("无准备粘贴数据！", MessageType.FAIL, this.page);
            return;
        }
        var paste = DataPaste.builder()
                .systemId(currentSystemId)
                .name(dataCopy.getName())
                .data(currentLayerTarget.getCode())
                .build();
        var spinnerDialog = SpinnerDialog.builder()
                .withProcessTip("正在执行数据粘贴...")
                .withContainer(Objects.requireNonNull(this.page))
                .build();
        spinnerDialog.show();
        LogUtils.info(log, "执行数据粘贴...");
        LogUtils.record(log, "请求数据，systemId：{},dataCopy:{},dataPaste:{}", this.currentSystemId, dataCopy, paste);
        CompletableFuture.supplyAsync(() -> analyzePasteService.unitEvalDataPaste(paste, dataCopy))
                .thenAccept(res -> Platform.runLater(() -> {
                    spinnerDialog.close();
                    if (res.isSuccess()) {
                        MessageDialog.builder()
                                .withType(MessageType.SUCCESS).withMessage("粘贴成功")
                                .withContainer(Objects.requireNonNull(this.page))
                                .build().show();
                        refreshFinishStateByLayerTarget();
                        loadUnitEvaluation(this.currentLayerTarget);
                    } else {
                        MessageDialog.builder()
                                .withType(MessageType.FAIL).withMessage(res.getMsg())
                                .withContainer(Objects.requireNonNull(this.page))
                                .build().show();
                    }
                }))
                .exceptionally((ex) -> {
                    spinnerDialog.close();
                    log.error("数据粘贴出错!", ex);
                    return null;
                });
    }

    public void refreshFinishStateByLayerTarget() {
        var state = systemProcessService.findUnitEvalProcess(this.currentSystemId)
                .stream()
                .filter(ps -> StringUtils.equals(ps.getName(), EvaluationModule.fromNameByUnitEval(currentLayerTarget.getTitle()).getName()))
                .map(SystemProcessDTO::getFinishState)
                .findFirst()
                .orElse(FinishState.NONE);
        refreshLayerFinishState(currentLayerTarget, state);
    }

    private void onDataCopyAction() {
        if (StringUtils.isBlank(currentLayerTarget.getTitle())) {
            return;
        }
        var module = EvaluationModule.fromNameByUnitEval(currentLayerTarget.getTitle());
        var copyData = DataCopy.builder()
                .copySystemId(this.currentSystemId)
                .name(module.getName())
                .data(this.currentLayerTarget.getCode())
                .state(SystemState.REPORT)
                .build();
        DataCopyUtils.copyClipboard(copyData);
        AppUtils.showMessageDialog("复制成功！", MessageType.SUCCESS, Objects.requireNonNull(this.page));
    }

    private void onReportContextMenuRequested() {
        if (StringUtils.isBlank(currentLayerTarget.getTitle())) {
            return;
        }
        var module = EvaluationModule.fromNameByUnitEval(currentLayerTarget.getTitle());
        this.enablePaste.set(DataCopyUtils.hasClipboard(module.getName(), SystemState.REPORT));
    }


    private void loadMenuData() {
        LogUtils.info(log, "获取层面指标树节点信息...");
        LogUtils.record(log, "请求数据:{}", this.currentSystemId);
        CompletableFuture.supplyAsync(() -> systemTargetService.findLayerTarget(this.currentSystemId))
                .thenAccept(res -> {
                    List<SystemProcessDTO> processDTOS = systemProcessService.findUnitEvalProcess(this.currentSystemId);
                    Platform.runLater(() -> {
                        if (res.isSuccess()) {
                            this.initMenu(res.getData(), processDTOS);
                        } else {
                            MessageDialog.builder()
                                    .withContainer(this.page)
                                    .withType(MessageType.FAIL)
                                    .withMessage("获取层面指标信息失败")
                                    .build().show();
                        }
                    });
                })
                .exceptionally((ex) -> {
                    log.error("获取层面指标树节点信息出错!", ex);
                    return null;
                });
    }

    private void initMenu(List<LayerTargetDTO> targets, List<SystemProcessDTO> process) {
        tecMenus.getItems().clear();
        manageMenus.getItems().clear();
        targets.stream().filter(t -> t.getType() == TargetType.TECHNOLOGY)
                .sorted(Comparator.comparingInt(LayerTargetDTO::getSort))
                .forEach(lt -> renderLayerMenuItem(lt, tecMenus, process));

        targets.stream().filter(t -> t.getType() == TargetType.MANAGEMENT)
                .sorted(Comparator.comparingInt(LayerTargetDTO::getSort))
                .forEach(lt -> renderLayerMenuItem(lt, manageMenus, process));
        tecMenus.getSelectionModel().select(0);
    }

    private void renderLayerMenuItem(LayerTargetDTO lt, ListView<MenuVO> menus, List<SystemProcessDTO> process) {
        FinishState finishState = process.stream()
                .filter(sp -> StringUtils.contains(sp.getName(), lt.getName()))
                .map(SystemProcessDTO::getFinishState)
                .findFirst().orElse(FinishState.NONE);
        var item = new MenuVO(0,lt.getTargetId(),lt.getName(),ControlUtils.finishStateToIcon(finishState));
        item.setState(finishState);
        menus.getItems().add(item);
    }


    private void loadUnitEvaluation(MenuVO layerMenuItem) {
        this.currentLayerTarget = layerMenuItem;
        currentLayerTargetLbl.setText(this.currentLayerTarget.getTitle());
        LogUtils.info(log, "获取单元测评信息...");
        LogUtils.record(log, "请求数据，systemId：{},targetId：{}", this.currentSystemId,
                currentLayerTarget.getCode());
        CompletableFuture.supplyAsync(() -> unitEvaluationService.findUnitEvaluationByLayerTarget(this.currentSystemId
                        , currentLayerTarget.getCode()))
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        this.unitResultAnalysisBox.setVisible(true);
                        this.emptyPane.setVisible(false);
                        var sheetData = res.getData().stream().map(UnitEvaluationViewMapper.INSTANCE::toVO).toList();
                        this.sheetView.loadContent(sheetData);
                    } else {
                        this.unitResultAnalysisBox.setVisible(false);
                        this.emptyPane.setVisible(true);
                        this.emptyLabel.setText(res.getMsg());
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("获取单元测评信息出错!", ex);
                    return null;
                });
    }

    private String enterProcess(String value){
        if(StringUtils.contains(value,"\\n")){
            return StringUtils.replace(value,"\\n","\n");
        }else{
            return value;
        }
    }

    private void batchSaveUnitEvaluation(boolean realTime,boolean finish){
        if(!this.sheetView.validate()){
            if(!realTime){
                AppUtils.showMessageDialog("以下标出的单元测评的必填信息不能为空",MessageType.WARN,this.page);
            }
            return;
        }
        var modifyData = this.sheetView.getModifyData().stream()
                .map(UnitEvaluationViewMapper.INSTANCE::toDTO)
                .toList();
        if (!realTime && CollectionUtils.isEmpty(modifyData)) {
            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
            refreshFinishProcess(finish);
            return;
        }
        LogUtils.info(log, "批量保存单元测评信息...");
        LogUtils.record(log, "请求数据，systemId：{},data:{}", this.currentSystemId, modifyData);
        //未保存的数据进行批量保存
        CompletableFuture.supplyAsync(() -> this.unitEvaluationService.batchSaveUnitEvaluation(modifyData),this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        //更新表数据
                        this.loadUnitEvaluation(this.currentLayerTarget);
                        if(!realTime){
                            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
                        }
                        refreshFinishProcess(finish);
                    } else {
                        if(realTime){
                            log.error("即时保存单元测评信息失败：{}",res.getMsg());
                        }else{
                            AppUtils.showMessageDialog(res.getMsg(),MessageType.FAIL,this.page);
                        }
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("批量保存单元测评信息出错!", ex);
                    return null;
                });
    }

    private void refreshFinishProcess(boolean finishSave) {
        FinishState state = finishSave ? FinishState.FINISH : FinishState.INCOMPLETE;
        LogUtils.info(log, "设置单元测评进度信息...");
        LogUtils.record(log, "请求数据，systemId：{},layerTargetId:{}",currentSystemId, currentLayerTarget.getCode());
        CompletableFuture.supplyAsync(() -> unitEvaluationService.setUnitEvalFinishState(currentSystemId, currentLayerTarget.getCode(), state))
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        refreshFinishState(state);
                    } else {
                        MessageDialog.builder()
                                .withContainer(this.page)
                                .withType(MessageType.FAIL).withMessage(res.getMsg())
                                .build().show();
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("设置单元测评进度信息出错!", ex);
                    return null;
                });
    }

    private void refreshFinishState(FinishState state) {
        EvaluationModule module = EvaluationModule.fromNameByUnitEval(currentLayerTarget.getTitle());
        LogUtils.info(log, "设置单元测评进度信息...");
        LogUtils.record(log, "请求数据，systemId：{},module:{},state:{}", this.currentSystemId, module, state);
        CompletableFuture.supplyAsync(() -> systemProcessService.setSystemProcess(this.currentSystemId, module, state))
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        refreshLayerFinishState(currentLayerTarget, state);
                    } else {
                        MessageDialog.builder()
                                .withContainer(this.page)
                                .withType(MessageType.FAIL).withMessage(res.getMsg())
                                .build().show();
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("设置单元测评进度信息出错!", ex);
                    return null;
                });
    }

    private void refreshLayerFinishState(MenuVO layerTarget, FinishState state) {
        layerTarget.setIcon(ControlUtils.finishStateToIcon(state));
        layerTarget.setState(state);
        tecMenus.refresh();
        manageMenus.refresh();
    }

}